package com.qianfeng.smartdevices.config;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.qianfeng.smartdevices.pojo.Menu;
import com.qianfeng.smartdevices.security.MySuccessHandler;
import com.qianfeng.smartdevices.service.MenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

import java.util.List;

/**
 * Created by jackiechan on 2021/10/18 11:06
 *
 * @author jackiechan
 * @version 1.0
 * @since 1.0
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private MySuccessHandler mySuccessHandler;

    private UserDetailsService myUserDetailsService;

    private BCryptPasswordEncoder passwordEncoder;


    private MenusService menusService;

    @Autowired
    public void setMenusService(MenusService menusService) {
        this.menusService = menusService;
    }

    @Autowired
    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void setMySuccessHandler(MySuccessHandler mySuccessHandler) {
        this.mySuccessHandler = mySuccessHandler;
    }

    @Autowired
    public void setMyUserDetailsService(UserDetailsService myUserDetailsService) {
        this.myUserDetailsService = myUserDetailsService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.csrf().disable();//禁用掉,不然需要添加 csrf 的头信息,或者是 post 请求会直接报 403
        List<Menu> allMenus = menusService.findAllMenus();//获取到所有的菜单,其实就是 url 地址和它需要什么权限
        allMenus.forEach(menu -> {
            try {
                //给每个地址设置需要的权限
                if (!ObjectUtils.isEmpty(menu.getUrl())) {
                    http.authorizeRequests().antMatchers(menu.getUrl()).hasAuthority(menu.getPerms());//设置每个地址需要的权限 //hasAnyAuthority()  hasAuthority()
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        http.authorizeRequests()
//                .mvcMatchers("/login", "/layui/**", "/js/**", "/websocket/**", "/colorcommand/**", "/humiture/**").permitAll()//符合前面的地址的路径都直接放行
                .and().formLogin()
                //.loginPage()//使用自己写的登录页面
                .loginProcessingUrl("/login")//自定义登陆的接口地址
                .successHandler(mySuccessHandler)
                .and().authorizeRequests().anyRequest().authenticated();//除了上面的请求地址之外,其他的地址都需要认证
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/js/**",
                "/layui/**",
                "/websocket/**",
                "/colorcommand/**", "/humiture/**", "/swagger-ui.html", "/webjars/**"


        );//和上面的).mvcMatchers("/login", "/layui/**", "/js/**", "/websocket/**", "/colorcommand/**", "/humiture/**").permitAll()效果是一样的
    }

    /**
     * 设置如何根据用户名查询用户信息以及密码的处理方式
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder);//设置如何从数据库中根据用户名查询数据并返回结果,并设置数据库中的密码是通过什么方式生成的
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //    @Bean
//    public CorsConfigurationSource corsConfigurationSource() {
//        CorsConfiguration configuration = new CorsConfiguration();
//        configuration.addAllowedOrigin("*");//修改为添加而不是设置，* 最好改为实际的需要，我这是非生产配置，所以粗暴了一点
//        configuration.addAllowedMethod("*");//修改为添加而不是设置
//        configuration.addAllowedHeader("*");//这里很重要，起码需要允许 Access-Control-Allow-Origin
//        configuration.setAllowCredentials(true);
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        source.registerCorsConfiguration("/**", configuration);
//        return source;
//    }
    @Bean
    @Lazy
    public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
        return new HandlerMappingIntrospector();
    }
}
